package com.strongbj.iot.devices.zebra.fx7500.response.handle;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.mot.rfid.api3.RfidStatusEvents;
import com.mot.rfid.api3.STATUS_EVENT_TYPE;
import com.mot.rfid.api3.TagData;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.hr.message.MQMessageOfHR;
import com.strongbj.iot.devices.hr.response.entity.ScanLabInfoOfDoor;
import com.strongbj.iot.devices.zebra.fx7500.response.entity.TagCache;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 对红外的处理
 * @author yuzhantao
 *
 */
public class InfraredHandle implements IMessageHandle<RfidStatusEvents,Object> {
	private static Logger logger = LogManager.getLogger(InfraredHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static final String ACTION_CODE = "collect020";
	
	private static ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); // 用于执行触发红外后，是否将标签信息发送到mq的线程池
	private TagCache tagCache;			// 标签缓存
	private int firstInventoryInfraredId=0;			// 第一次触发的红外传感器id
	private String firstInventoryInfraredDirection=""; // 第一次的红外出发方向
	private long lastInventoryInfraredTime=0;		// 最后一次红外触发的时间
	private long scanSpaceMillisecond = 2000;		// 扫描的间隔毫秒数
	private String hostIp;			// 当前Fx7500的IP
	private String direction;		// 当前Fx7500针对两条红外线的方向
	
	public InfraredHandle(TagCache tagCache,String hostIp,String direction){
		this.tagCache=tagCache;
		this.hostIp = hostIp;
		this.direction=direction;
	}
	
	@Override
	public boolean isHandle(RfidStatusEvents t) { 
		STATUS_EVENT_TYPE statusType = t.StatusEventData.getStatusEventType();
		if(statusType == STATUS_EVENT_TYPE.GPI_EVENT){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, RfidStatusEvents t) {
		int gpiPort = t.StatusEventData.GPIEventData.getGPIPort();  // 1\2为两个红外信息
//		System.out.println("gpiPort="+gpiPort);
		this.lastInventoryInfraredTime=System.currentTimeMillis();
		if(firstInventoryInfraredId==0){
			this.firstInventoryInfraredId=gpiPort;  // 获取第一次触发红外的传感器ID
			
			// 设置触发的方向，用来传递给MQ
			if(this.firstInventoryInfraredId==1){
				this.firstInventoryInfraredDirection=this.direction;
			}else{
				if(this.direction.equals("I")){
					this.firstInventoryInfraredDirection="E";
				}else if(this.direction.equals("E")){
					this.firstInventoryInfraredDirection="I";
				}else{
					this.firstInventoryInfraredDirection="?";
				}
			}
			
			this.tagCache.clear();		// 当系统判断是第一次触发红外信号后，清除之前缓存中保留的标签数据
			InfraredHandle.cachedThreadPool.execute(new RfidRunnable());
		}
		return null;
	}

	/**
	 * 通过最后一次触发红外的时间，倒计时判断是否将已扫到的标签数据上传到MQ的线程
	 * @author jeff
	 *
	 */
	class RfidRunnable implements Runnable{

		@Override
		public void run() {
			// 循环判断最后一次触发红外的时间是否超过scanSpaceMillisecond毫秒
			while(lastInventoryInfraredTime+scanSpaceMillisecond>System.currentTimeMillis()){
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

//			System.out.println("红外出发超过"+scanSpaceMillisecond+"毫秒");
//			for(TagData tg : tagCache.getTags()){
//				System.out.println("标签数据："+tg.getTagID());
//			}
			
			lastInventoryInfraredTime=0;	// 初始化最后一次触发红外的时间
			firstInventoryInfraredId=0;		// 初始化第一次触发红外的红外传感器ID
			// 如果扫到的标签数大于0，就发送信息到mq
			if(tagCache.size()>0) {
				this.sendMessage();
			}
		}
		
		/**
		 * 发送门禁扫描到的标签信息到MQ
		 */
		private void sendMessage(){
			MQMessageOfHR msg = new MQMessageOfHR();
			msg.setActioncode(ACTION_CODE);
			ScanLabInfoOfDoor slid = new ScanLabInfoOfDoor();
			slid.setDevIp(hostIp);
			slid.setDirection(firstInventoryInfraredDirection); // 获取该门禁此时实际的方向
			List<String> list = new ArrayList<String>();
			for(TagData tg : tagCache.getTags()){
				list.add(tg.getTagID());
			}
			slid.setRfids(list);
			msg.setAwsPostdata(slid);
			String json = JSON.toJSONString(msg);
			topicSender.send("ZebraFx7500ToService", json);
			logger.info("HR设备 向MQ发送标签数据	 JSON={}", json);
		}
	}
}
